package income

import (
	"strings"
	"week13/errors"
	"week13/internal/data"
	"week13/pkg/constant"
	"week13/pkg/orm"
)

const TABLENAME = "income"
type IncomeDo struct {
	Id int64 `json:"id" xorm:"pk autoincr BIGINT id <-"`
	Amount int `json:"amount" xorm:"INT amount"`
	DealId int64 `json:"dealId" xorm:"BIGINT dealid"`
	AgentId int64 `json:"agentId" xorm:"BIGINT agentid"`
	Rate int `json:"rate" xorm:"INT rate"`
	SettleTime int `json:"settleTime" xorm:"INT settle_time"`
	State int `json:"state" xorm:"INT state"`
	BizType int `json:"bizType" xorm:"biz_type"`
	Addtime int `json:"addtime" xorm:"INT created addtime"`
	Mtime string `json:"mtime" xorm:"TIMESTAMP mtime updated"`
}
type IncomeWhere struct {
	Id []interface{} `column:"id"`
	Amount []interface{} `column:"amount"`
	DealId []interface{} `column:"dealid"`
	AgentId []interface{} `column:"agentid"`
	SettleTime []interface{} `column:"settle_time"`
	State []interface{} `column:"state"`
	BizType []interface{} `column:"biztype"`
	Addtime []interface{} `column:"addtime"`
}
func(income IncomeDo) TableName() string{
	return TABLENAME
}
//数据访问接口
type IncomeRepository interface {
	Find(incomeId int64) (IncomeDo,error)
	Save(income IncomeDo) (int64,error)
	List(do IncomeDo,page int,pageSize int) ([]IncomeDo,error)
	FindOneByFilter(Do IncomeDo) (IncomeDo,error)
	Count(Do IncomeDo) (int64,error)
	ListByWhere(where orm.Where,page int,pageSize int) ([]IncomeDo,error)
	CountByWhere(where orm.Where)(int64,error)
}

type IncomeDao struct {
}
//根据Where 查找
func (dao *IncomeDao) ListByWhere(where orm.Where,page int,pageSize int) ([]IncomeDo,error){
	db,err := data.DBEngin()
	if err != nil {
		return nil,errors.NewConnectFail()
	}
	whereStr, vales := where.GetWhereSqlAndValue()
	incomes := make([]IncomeDo,0)
	if page>=1 {
		db.Where(whereStr, vales...).Limit(pageSize,(page-1)*pageSize).Find(&incomes)
	} else {
		db.Where(whereStr, vales...).Find(&incomes)
	}
	return incomes,nil
}
//根据Where 统计
func (dao *IncomeDao) CountByWhere(where orm.Where)(int64,error){
	db,err := data.DBEngin()
	if err != nil {
		return 0,errors.NewConnectFail()
	}
	whereStr, vales := where.GetWhereSqlAndValue()
	do2 := new(IncomeDo)
	total, err := db.Where(whereStr, vales...).Count(do2)
	if err != nil {
		return 0,errors.NewExecuteFail(err.Error())
	}
	return total,nil
}
//统计
func (dao *IncomeDao) Count(Do IncomeDo)(int64,error){
	db,err := data.DBEngin()
	if err != nil {
		return 0,errors.NewConnectFail()
	}
	where := make([]string,0)
	values := make([]interface{}, 0)
	if Do.DealId >0 {
		where = append(where,"dealid=?")
		values = append(values,Do.DealId)
	}
	if Do.AgentId >0 {
		where  = append(where,"agentid=?")
		values = append(values,Do.AgentId)
	}
	if Do.Id >0 {
		where  = append(where,"id=?")
		values = append(values,Do.Id)
	}
	if len(where)<1{
		return 0,errors.NewIllegalParam("Find One income  lack where params")
	}
	whereStr := strings.Join(where," AND ")
	do2 := new(IncomeDo)
	total, err := db.Where(whereStr, values...).Count(do2)
	if err != nil {
		return 0,errors.NewExecuteFail(err.Error())
	}
	return total,nil
}
func (dao *IncomeDao) FindOneByFilter(Do IncomeDo) (IncomeDo,error)  {
	db,err := data.DBEngin()
	if err != nil {
		return IncomeDo{},errors.NewConnectFail()
	}
	where := make([]string,0)
	values := make([]interface{},0)
	if Do.DealId >0 {
		where = append(where,"dealid=?")
		values = append(values,Do.DealId)
	}
	if Do.AgentId >0 {
		where  = append(where,"agentid=?")
		values = append(values,Do.AgentId)
	}
	if Do.Id >0 {
		where  = append(where,"id=?")
		values = append(values,Do.Id)
	}
	if len(where)<1{
		return IncomeDo{},errors.NewIllegalParam("Find One income  lack where params")
	}
	whereStr := strings.Join(where," AND ")
	data := IncomeDo{}
	ret,err := db.Where(whereStr,values...).Get(&data)
	if !ret {
		return data, errors.NewNoFound()
	}
	if err != nil {
		return data,errors.NewExecuteFail(err.Error())
	}
	return data,nil
}
func (dao *IncomeDao) List(Do IncomeDo,page int,pageSize int) ([]IncomeDo,error)  {
	db,err := data.DBEngin()
	if err != nil {
		return nil,errors.NewConnectFail()
	}
	where := make([]string,0)
	values := make([]interface{}, 0)
	if Do.DealId >0 {
		where = append(where,"dealid=?")
		values = append(values,Do.DealId)
	}
	if Do.AgentId >0 {
		where  = append(where,"agentid=?")
		values = append(values,Do.AgentId)
	}
	if Do.Id >0 {
		where  = append(where,"id=?")
		values = append(values,Do.Id)
	}
	if Do.State >0 {
		where  = append(where,"state=?")
		values = append(values,Do.State)
	}
	if Do.SettleTime >0{
		where  = append(where,"settle_time = ?")
		values = append(values,Do.SettleTime)
	}
	if len(where)<1{
		return nil,errors.NewIllegalParam("Find One income  lack where params")
	}
	whereStr := strings.Join(where," AND ")
	incomes := make([]IncomeDo,0)
	if page>=1 {
		db.Where(whereStr,values...).Limit(pageSize,(page-1)*pageSize).Find(&incomes)
	} else {
		db.Where(whereStr,values...).Find(&incomes)
	}
	if err != nil {
		return nil, errors.NewExecuteFail("income list error")
	}
	return incomes,nil
}

func (dao *IncomeDao) Find(incomeId int64) (IncomeDo,error)  {
	db,err := data.DBEngin()
	if err != nil {
		return IncomeDo{},errors.NewConnectFail()
	}
	incomeDO := IncomeDo{}
	ret,err := db.ID(incomeId).Get(&incomeDO)
	if !ret {
		return incomeDO, errors.NewNoFound()
	}
	if err != nil {
		return incomeDO,errors.NewExecuteFail(err.Error())
	}
	return incomeDO,nil
}
func (dao *IncomeDao) Save(do IncomeDo) (int64, error)   {
	db,err := data.DBEngin()
	if err != nil {
		return 0,errors.NewConnectFail()
	}
	var affected int64=0
	if do.Id == 0 {
		affected,err = db.Insert(&do)
		if err !=  nil {
			return affected, errors.NewExecuteFail(err.Error())
		}
		if affected ==0 {
			return affected,errors.NewExecuteFail("INSERT ERROR")
		}
		return do.Id,nil
	}
	id := do.Id
	do.Id = 0
	affected, err = db.ID(id).Update(do)
	if err !=  nil {
		return affected, errors.NewExecuteFail(err.Error())
	}
	if affected == 0 {
		return affected, errors.NewNothingChange()
	}
	return id,nil
}
//获取可结算的收入
func GetCanSettleIncome(settleTime []int,agentId int64,page,pageSize int) ([]IncomeDo,error){
	if len(settleTime) != 2 {
		return nil, errors.NewIllegalParam("settleTime must [begin,end]")
	}
	db,err := data.DBEngin()
	if err != nil {
		return nil,errors.NewConnectFail()
	}
	where := make([]string,0)
	values := make([]interface{}, 0)
	where = append(where,"state=?","settle_time>=? and settle_time<?")
	values = append(values,constant.INCOME_STATE_INIT,settleTime[0],settleTime[1])
	if agentId>0{
		where = append(where,"agentid=?")
		values = append(values,agentId)
	}
	whereStr := strings.Join(where," AND ")
	incomes := make([]IncomeDo,0)
	if page>=1 {
		db.Where(whereStr,values...).Limit(pageSize,(page-1)*pageSize).Find(&incomes)
	} else {
		db.Where(whereStr,values...).Find(&incomes)
	}
	if err != nil {
		return nil, errors.NewExecuteFail("income list error")
	}
	return incomes,nil
}